<template>
	<view class="leaflet-map-wrapper">
		<!-- #ifdef H5 -->
		<view class="map-container">
			<div :id="mapId" class="leaflet-map"></div>
		</view>
		<!-- #endif -->
		<!-- #ifndef H5 -->
		<view class="map-not-supported">
			<text>地图功能仅在H5端可用</text>
		</view>
		<!-- #endif -->
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'

// #ifdef H5
import L from 'leaflet'
// #endif

const props = defineProps({
	// 地图容器ID，必须唯一
	mapId: {
		type: String,
		required: true
	},
	// 初始中心点坐标 [纬度, 经度]
	center: {
		type: Array,
		default: () => [40.25, 122.7]
	},
	// 初始缩放级别
	zoom: {
		type: Number,
		default: 8
	},
	// 最小缩放级别
	minZoom: {
		type: Number,
		default: 4
	},
	// 最大缩放级别
	maxZoom: {
		type: Number,
		default: 18
	},
	// 地图类型: 'terrain'(地形), 'satellite'(影像), 'street'(街道)
	mapType: {
		type: String,
		default: 'terrain'
	},
	// 是否自动初始化地图
	autoInit: {
		type: Boolean,
		default: true
	},
	showAnnotation: {
		type: Boolean,
		default: false
	}
})

const emit = defineEmits(['map-ready', 'map-error'])

// 天地图配置
const Tiandi = {
	TK: '324ecd6881be3d4e5c5439de4c164e92',
	P: '&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=',
	// 天地图 - 街道图
	VEC: 'https://t{s}.tianditu.gov.cn/vec_w/wmts?layer=vec',
	VEC_ANNO: 'https://t{s}.tianditu.gov.cn/cva_w/wmts?layer=cva',
	// 天地图 - 影像图
	IMG: 'https://t{s}.tianditu.gov.cn/img_w/wmts?layer=img',
	IMG_ANNO: 'https://t{s}.tianditu.gov.cn/cia_w/wmts?layer=cia',
	// 天地图 - 地形图
	TER: 'https://t{s}.tianditu.gov.cn/ter_w/wmts?layer=ter',
	TER_ANNO: 'https://t{s}.tianditu.gov.cn/cta_w/wmts?layer=cta'
}
const urlSuffix = `${Tiandi.P}${Tiandi.TK}`

// 地图实例
let map = null
let baseLayer = null
let annoLayer = null
let initializing = false

// 暴露地图实例给父组件
const getMapInstance = () => map

// 初始化地图
const initMap = async () => {
	// #ifdef H5
	if (initializing || map) {
		return
	}
	initializing = true
	console.log(`[LeafletMap ${props.mapId}] 开始初始化地图...`)
	
	// 确保在DOM更新后获取容器
	await nextTick()
	
	// 获取地图容器DOM元素
	const container = document.getElementById(props.mapId)
	console.log(`[LeafletMap ${props.mapId}] 通过ID查询结果:`, container)
	
	if (!container) {
		console.error(`[LeafletMap ${props.mapId}] 地图容器未找到，请检查DOM结构`)
		emit('map-error', new Error('地图容器未找到'))
		initializing = false
		return
	}
	
	// 防御：清理可能残留的Leaflet绑定与子节点
	if (container._leaflet_id) {
		try { delete container._leaflet_id } catch {}
		try { container.innerHTML = '' } catch {}
	}
	
	// 确保容器有正确的尺寸
	console.log(`[LeafletMap ${props.mapId}] 容器初始尺寸:`, container.offsetWidth, 'x', container.offsetHeight)
	if (container.offsetWidth === 0 || container.offsetHeight === 0) {
		console.warn(`[LeafletMap ${props.mapId}] 地图容器尺寸为0，等待容器渲染完成`)
		await new Promise(resolve => setTimeout(resolve, 500))
		console.log(`[LeafletMap ${props.mapId}] 等待后容器尺寸:`, container.offsetWidth, 'x', container.offsetHeight)
	}
	
	// 如果容器尺寸仍然为0，强制设置最小尺寸
	if (container.offsetWidth === 0 || container.offsetHeight === 0) {
		console.warn(`[LeafletMap ${props.mapId}] 强制设置容器最小尺寸`)
		container.style.width = '100%'
		container.style.height = '400px'
		container.style.minHeight = '400px'
	}
	
	try {
		console.log(`[LeafletMap ${props.mapId}] 初始化地图，最终容器尺寸:`, container.offsetWidth, 'x', container.offsetHeight)
		
		// 检查Leaflet是否可用
		if (typeof L === 'undefined') {
			console.error(`[LeafletMap ${props.mapId}] Leaflet库未加载`)
			emit('map-error', new Error('Leaflet库未加载'))
			return
		}
		
		// 创建地图
		map = L.map(container, {
			minZoom: props.minZoom,
			maxZoom: props.maxZoom
		}).setView(props.center, props.zoom)
		console.log(`[LeafletMap ${props.mapId}] 地图对象创建成功:`, map)
		
		// 根据地图类型添加底图
		addBaseLayer(props.mapType)
		
		// 移除默认的attribution控件（包含乌克兰图标）
		map.attributionControl.remove()
		
		// 强制刷新地图
		setTimeout(() => {
			if (map) {
				console.log(`[LeafletMap ${props.mapId}] 强制刷新地图尺寸`)
				map.invalidateSize()
			}
		}, 100)
		
		console.log(`[LeafletMap ${props.mapId}] 地图初始化完成`)
		
		// 通知父组件地图已就绪
		emit('map-ready', map)
		
	} catch (error) {
		console.error(`[LeafletMap ${props.mapId}] 地图初始化失败:`, error)
		console.error('错误堆栈:', error.stack)
		emit('map-error', error)
	} finally {
		initializing = false
	}
	// #endif
}

// 添加底图图层
const addBaseLayer = (type) => {
	// #ifdef H5
	if (!map) return
	
	// 移除旧图层
	if (baseLayer) {
		map.removeLayer(baseLayer)
		baseLayer = null
	}
	if (annoLayer) {
		map.removeLayer(annoLayer)
		annoLayer = null
	}
	
	let baseUrl = ''
	let annoUrl = ''
	
	switch (type) {
		case 'satellite':
			baseUrl = `${Tiandi.IMG}${urlSuffix}`
			annoUrl = `${Tiandi.IMG_ANNO}${urlSuffix}`
			break
		case 'street':
			baseUrl = `${Tiandi.VEC}${urlSuffix}`
			annoUrl = `${Tiandi.VEC_ANNO}${urlSuffix}`
			break
		case 'terrain':
		default:
			baseUrl = `${Tiandi.TER}${urlSuffix}`
			annoUrl = `${Tiandi.TER_ANNO}${urlSuffix}`
			break
	}
	
	// 添加底图
	baseLayer = L.tileLayer(baseUrl, {
		subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
		attribution: '© 天地图'
	})
	baseLayer.addTo(map)
	
	if (props.showAnnotation) {
		annoLayer = L.tileLayer(annoUrl, {
			subdomains: ['0', '1', '2', '3', '4', '5', '6', '7']
		})
		annoLayer.addTo(map)
	}
	
	console.log(`[LeafletMap ${props.mapId}] 底图图层添加成功:`, type)
	// #endif
}

// 切换地图类型
const changeMapType = (type) => {
	addBaseLayer(type)
}

// 刷新地图尺寸
const invalidateSize = () => {
	// #ifdef H5
	if (map) {
		map.invalidateSize()
	}
	// #endif
}

// 设置地图中心和缩放
const setView = (center, zoom) => {
	// #ifdef H5
	if (map) {
		map.setView(center, zoom)
	}
	// #endif
}

// 监听地图类型变化
watch(() => props.mapType, (newType) => {
	if (map) {
		changeMapType(newType)
	}
})

// 组件挂载时初始化
onMounted(() => {
	if (props.autoInit) {
		// 延迟初始化，确保DOM完全渲染
		setTimeout(() => {
			initMap()
		}, 100)
	}
})

// 组件卸载时清理
onUnmounted(() => {
	// #ifdef H5
	if (map) {
		console.log(`[LeafletMap ${props.mapId}] 销毁地图实例`)
		try { map.remove() } catch {}
		map = null
	}
	baseLayer = null
	annoLayer = null
	const container = document.getElementById(props.mapId)
	if (container) {
		try { delete container._leaflet_id } catch {}
		try { container.innerHTML = '' } catch {}
	}
	// #endif
})

// 暴露方法给父组件
defineExpose({
	getMapInstance,
	initMap,
	changeMapType,
	invalidateSize,
	setView
})
</script>

<style scoped>
.leaflet-map-wrapper {
	width: 100%;
	height: 100%;
}

.map-container {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
	overflow: hidden;
	background: #f5f5f5;
	position: relative;
}

/* Leaflet地图DOM元素样式 */
.leaflet-map {
	width: 100%;
	height: 100%;
	min-height: 800rpx; /* 设置最小高度确保地图可见 */
	border-radius: 12rpx;
}

/* Leaflet地图样式覆盖 */
.map-container :deep(.leaflet-container) {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
}

.map-container :deep(.leaflet-popup-content-wrapper) {
	border-radius: 8rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.map-container :deep(.leaflet-popup-content) {
	margin: 12rpx 16rpx;
	font-size: 24rpx;
	line-height: 1.4;
}

.map-container :deep(.leaflet-control-attribution) {
	font-size: 20rpx;
	background: rgba(255, 255, 255, 0.8);
}

.map-not-supported {
	text-align: center;
	padding: 100rpx 40rpx;
	color: #6c757d;
	font-size: 28rpx;
	background: #f8f9fa;
	border-radius: 12rpx;
}
</style>

